/*
 * @Author: lbt666 1319451895@qq.com
 * @Date: 2022-04-13 15:49:26
 * @LastEditors: lbt666 1319451895@qq.com
 * @LastEditTime: 2023-07-30 15:02:44
 * @Description: 请求封装
 */
import axios, { AxiosResponse } from 'axios'
import { Toast, Dialog } from 'vant'
import { getToken, removeToken } from '@/utils/auth'
import type { configData } from './asioxType'
import { userAuthorization } from '@/utils/LoginAuthorization'
import contractStore from '@/store/modules/contract'
import * as login from '@/contractInstantiation'

let loadingInstance: any = null //这里是loading
//使用create方法创建axios实例

export const Service = axios.create({
  timeout: 0, // 请求超时时间
  baseURL: 'http://dapp.bblove.club',
  // baseURL: 'http://www.bblove.club/dev-api',
  // baseURL: '/dev-api',
  headers: {
    'Content-Type': 'application/json'
  }
})
// 添加请求拦截器
Service.interceptors.request.use((config: configData): configData | Promise<configData> => {
  if (config && config.loading) {
    loadingInstance = Toast.loading({
      duration: 0,
      message: '加载中',
      forbidClick: true
    });
  }
  config.headers['Authorization'] = getToken()
  config.headers['Accept-Language'] = localStorage.getItem('language') === 'zh' ? 'zh-CN,zh;q=0.9,en;q=0.8' : 'zh-cn;q=0.8,en-US;q=0.9'
  return config
})
// 添加响应拦截器
Service.interceptors.response.use((response: AxiosResponse): any => {
  contractStore().SET_NetWork(true)
  if (loadingInstance) loadingInstance.clear()
  let data = response.data
  if (data.status === 200) {
    return data
  } else if (data.status === 401) {
    // if (getToken()) {
    // 重新登录
    Dialog.confirm({
      title: '提示',
      message: '签名已失效，请重新签名',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      confirmButtonColor: '#1F75D9',
    })
      .then(() => {
        removeToken()
        localStorage.removeItem('sign')
        localStorage.removeItem('signDestry')
        userAuthorization(contractStore(), async (res: boolean) => {
          if (res) {
            // await login.queryAllowance()
          }
        })
      })
    // }
  } else {
    Toast(data.message || '系统错误，请稍后再试')
    return data
  }
}, error => {
  console.log('Api请求错误', error)
  contractStore().SET_NetWork(false)
  const msg = error.message !== undefined ? error.message : ''
  Toast.loading({
    forbidClick: true,
    message: msg ? msg : '网络错误'
  });
  return Promise.reject(error)
})
